/*
 * miniFreeRTOS SOC System emulation.
 *
 * Copyright (c) 2024- yanl1229@163.com.
 * Written by yanl1229
 *
 * This code is licensed under the GPL.
 */

#ifndef TASK_H
#define TASK_H


#include "list.h"
#include "irq.h"

/* Constants required to set up the initial stack. */
#define INITIAL_XPSR_VAL                        0x01000000
#define INITIAL_EXC_START_MSK                   0xfffffffe
#define INITIAL_EXC_RETURN                      0xfffffffd

extern uint32_t SystemCoreClock;
extern struct task_struct * volatile current;

#define MAX_DELAY              0xffffffffUL

#define STACK_ALIGNMENT_MASK    0x7

#define CONFIG_SYSTICK_CLOCK            (SystemCoreClock)
#define HZ                              1000
#define TICK_PERIOD_MS                  (1000 / HZ)
#define CONFIG_MAX_PRIORITIES           32
#define CONFIG_MINIMAL_STACK_SIZE       128
#define CONFIG_MAX_TASK_NAME_LEN         16
#define CONFIG_TASK_IDLE_PRIORITY       0

/*
 * 任务管理描述符
 */
struct task_struct
{
    volatile uint32_t * stack_top;          /* must be first */
    struct list_node delay_node;            /* 任务延迟队列节点 */
    struct list_node run_node;              /* 任务运行队列节点 */
    struct list_node event_node;            /* 任务事件队列节点 */
    unsigned long prio;                     /* 任务运行时优先级 */
    unsigned long static_prio;              /* 任务静态优先级 */
    unsigned long mutex_count;              /* 任务持有的互斥锁计数器 */
    unsigned long in_ready;                 /* 任务是否在运行队列 */
    uint32_t *stack;                        /* 任务栈底部 */
    char name[CONFIG_MAX_TASK_NAME_LEN];
};

enum sched_stat {
    SCHED_STOP,
    SCHED_SUSPEND,
    SCHED_RUNNIING,
};

extern struct task_struct *task_create(void(task_fn)(void*),
                        char *name,
                        uint16_t length,
                        void *args,
                        unsigned long prio);


extern volatile uint32_t jiffies;
extern void task_delete(struct task_struct * p);
extern void task_delay(uint32_t ticks);
extern void sched_init(void);
extern void sched_start(void);
extern void sched_suspend(void);
extern long sched_resume(void);
extern long update_tick(void);
extern void switch_context(void);
extern long get_sched_stat(void);
extern void sched_tick(void);
extern void yield(void);
extern uint32_t get_tick(void);
extern uint32_t get_high_priority(void);
extern void enqueue_task(struct task_struct * task);
extern void dequeue_task(struct task_struct * task);
extern list_head get_queue_by_priority(uint8_t priority);
extern uint32_t get_tasks(void);
extern uint32_t remove_from_event_queue(list_head list);
extern void add_delayed_list(uint32_t relative_timeout);
#endif
